import { API } from "@/api/api";
import { Operation, Power, SearchPowerInput } from "@/api/api.model";
import { Menu_AllFields } from "@/modal/commonModal";
import { UseFormService } from "@/utils/useCommon/use.form.service";
import { UseQuery } from "@/utils/useCommon/use.query";
import { UseTableService } from "@/utils/useCommon/use.table.service";
import { TableColumnType, TreeSelectProps } from "ant-design-vue";
import { ColumnType } from "ant-design-vue/lib/table";
import { ref, watch } from "vue";

/////////////////表单/////////////////

export class PowerFormService extends UseFormService<Power> {

	public openations: Array<{ label: string, value: string }> = [
		{ label: '查看', value: Operation.SHOW },
		{ label: '新增', value: Operation.ADD },
		{ label: '编辑', value: Operation.UPDATE },
		{ label: '删除', value: Operation.DELETE },
		{ label: '导出', value: Operation.EXPORT },
		{ label: '导入', value: Operation.IMPORT },
	]

	treeData = ref<TreeSelectProps['treeData']>([]);

	private menuIdMap: any = [];
	public showForm = ref(false);

	async initForm(info?: Power): Promise<Power> {
		this.getMenuList();
		return {
			_id: 0,
			name: '',
			code: '',
			menuId: 0,
			sortCode: 99999,
			operation: []
		}
	}

	createRule() {
		return {
			menuId: [this.isRequired('菜单')],
			name: [this.isRequired('权限名称')]
		}
	}

	onSubmit(info: Power, otherInfo: any) {
		info.menu = info.menuId as any;
		info.explain = info.explain || '';
		delete info.menuId;
		info.sortCode = Number(info.sortCode) || 99999;
		this.saveData(info, (status) => {
			if (status) this.showForm.value = false;
		});
	}

	onSelectMenu(value: number) {
		if (this.modelRef._id === 0) {
			const menu = this.menuIdMap[value];
			this.modelRef.name = menu.label;
			this.modelRef.code = menu.name;
		}
	}

	public onAdd() {
		this.modelRef._id = 0;
		this.modelRef.menuId = 0;
		this.modelRef.operation = [];
		this.modelRef.sortCode = 99999;
		this.modelRef.code = '';
		this.modelRef.name = '';	
		this.showForm.value = true;
	}

	public onEdit(id) {
		this.showForm.value = true;
		this.getPoswerById(id);
	}

	private getMenuList() {
		API.Query.findAllMenus(Menu_AllFields).then(restData => {
			if (restData) {
				const menuTree = this.setMenuTree(restData);
				this.treeData.value = menuTree;
			}
		})
	}

	private getPoswerById(id: number) {
		API.Query.findPowerById(id, ['_id', 'name', 'code', 'operation', 'menu._id'])
			.then((response) => {
				if (response) {
					const data = response;
					this.modelRef._id = data._id;
					this.modelRef.name = data.name;
					this.modelRef.code = data.code;
					this.modelRef.menuId = data.menu._id;
					this.modelRef.operation = data.operation;
				}
			});
	}

	private setMenuTree(menuList: any[]): any {
		const newMenus = menuList.map(element => {
			let obj = Object.assign({}, element);
			obj.id = element._id || 0;
			return { name: obj.name, label: obj.title, value: obj.id, children: [], parentStr: obj.parent || null };
		});

		this.menuIdMap = newMenus.reduce((p, c) => {
			p[c.value] = c;
			return p;
		}, {});

		const menuMap = newMenus.reduce((p, c) => {
			p[c.name] = c;
			return p;
		}, {});

		newMenus.forEach((menu) => {
			if (menu.parentStr) {
				const parent = menuMap[menu.parentStr];
				parent.children = parent.children ?? [];
				parent.children.push(menu);
			}
		});
		return newMenus.filter((menu) => !menu.parentStr);
	}
}


/////////////////表格列表/////////////////

/**
 * 列表查找分页
 */
export class PowerTableService extends UseTableService<Power, SearchPowerInput> {

	getPageWhere(): SearchPowerInput {
		this.sorter = { sortCode: 1 };
		return { name: UseQuery.regex(this.keyword.value) };
	}

	/**
	 * 获取表格列
	 * @date 2022-03-10
	 * @return {any}
	 */
	public columns(): TableColumnType<{}>[] {
		const columns: ColumnType[] = [
			{ ...this.getColumns('序号', 'rowIndex') },
			{ ...this.getColumns('标题', 'name') },
			{ ...this.getColumns('菜单', 'menu.name') },
			{ ...this.getColumns('排序', 'sortCode') },
			{ ...this.getColumns('权限', 'operation') },
			{ ...this.getColumns('操作', 'action'), width: 150, fixed: 'right' },
		]
		return columns
	}
}